package com.white.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) {

        ServerSocket ServerSocket = null;//开放的套接字
        Socket socket = null;//链接客户端的套接字
        Scanner fromKey = null;//键盘输入流
        Scanner fromClient = null;//获取从客户端读的字节流
        PrintWriter toClient = null;//获取向客户端写的字节流

        try {
            ServerSocket = new ServerSocket(8866);
            System.out.println("服务器已启动,等待客户端链接");
            //链接客户端的套接字
            socket = ServerSocket.accept();

            //实例化向客户端写的字节流
            toClient = new PrintWriter(socket.getOutputStream());
            toClient.println("你好啊客户端!!!");
            toClient.flush();
            System.out.println("我(服务器端) : 你好啊客户端!!!");
            /*
             * 注意:服务器端与客户端不能都先获取输入流,这样会导致socket阻塞
             * */
            //实例化从服务器读的字节流
            fromClient = new Scanner(socket.getInputStream());
            //实例化键盘输入流
            fromKey = new Scanner(System.in);
            //阻塞等待客户端发送消息
            while(true){
                String fromClientData = fromClient.nextLine();
                System.out.println("客户端 :" + fromClientData);
                System.out.print("我(服务器端) :");
                //获取输入的数据
                String toClientData = fromKey.nextLine();
                //发送给客户端
                toClient.println(toClientData);
                toClient.flush();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                assert fromClient != null;
                fromClient.close();
                toClient.close();
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }

}
